package com.example.securitylianxi.controller;

import com.example.securitylianxi.domain.AjaxResult;
import com.example.securitylianxi.domain.AuthUser;
import com.example.securitylianxi.domain.LoginUser;
import com.example.securitylianxi.service.AuthUserService;
import com.example.securitylianxi.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class LoginSuccessController {

    @Autowired
    private AuthUserService authUserService;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/test")
    @PreAuthorize("hasAuthority('xixi')")
    public String test() {
        return "登陆成功";
    }

    @GetMapping("/admin")
    @PreAuthorize("hasAuthority('admin')")
    public String test2() {
        return "admin权限";
    }

    @PostMapping("/user/login")
    public AjaxResult login(@RequestBody AuthUser authUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(authUser.getUsername(), authUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (ObjectUtils.isEmpty(authenticate)) {
            throw new RuntimeException("账号或密码错误");
        }
        LoginUser user = (LoginUser) authenticate.getPrincipal();
        user.getPermission().forEach(System.out::println);
        String id = user.getAuthUser().getId().toString();

        redisTemplate.boundValueOps("login_user:" + id).set(user);
        redisTemplate.boundValueOps("login_user:" + id).expire(60 * 60 * 24, TimeUnit.SECONDS);

        String token = JwtUtil.createJWT(id, 60L * 60 * 24);

        return AjaxResult.success("登陆成功", token);
    }

    @GetMapping("/user/getAuthentication")
    public LoginUser getAuthentication(Authentication authentication){
        return (LoginUser) authentication.getDetails();
    }
}
